<?php

namespace SDXApi\Service;


use SDXApi\Adapters\HomeTemplateAdapter;
use SDXApi\Model\HomeTemplateModel;
use SDXApi\Model\HomeTemplateStencilNewModel;
use SDXApi\Repositories\GoodsRepository;


class HomeTemplatesNewService
{

	/**
	 * @var HomeTemplateModel
	 */
	protected $templateModel;

    /**
     * @var HomeTemplateStencilNewModel
     */
	protected $templateStencilModel;

	/**
	 * @var
	 */
	public $isShow;

	/**
	 * @var
	 */
	protected $errorMessage;

	/**
	 * @var
	 */
	protected $userId;

	/**
	 * @var
	 */
	protected $wid;

    protected $goodsRepository;

	/**
	 * HomeTemplatesService constructor.
	 * @param int $userId
	 * @param int $wid
	 */
	public function __construct($userId = 0, $wid = 8)
	{
		$this->templateModel = new HomeTemplateModel();
		$this->templateStencilModel = new HomeTemplateStencilNewModel();
        $this->goodsRepository = new GoodsRepository();

		$this->userId = empty($userId) ? 0 : $userId + 0;
		$this->wid = empty($wid) ? 0 : $wid + 0;
	}

    /**
     * 获取首页模版
     * @author Jerry
     * @param $groupId
     * @param int $pageNumber
     * @return array|bool
     */
	public function getHomeTemplateByGroup($groupId, $pageNumber = 1)
	{

		$group = $this->findHomeTemplateByGroup($groupId);

		if (empty($group)) {
			return false;
		}

		$templateName = $this->getHomeTemplateGroupName($groupId);

		$data = $this->checkHomeTemplateGroupData($group, $pageNumber);
		$data['name'] = $templateName['name'];
		return $data;
	}

	/**
	 *
	 * Created by Jerry
	 * @param $groupId
	 * @return bool|mixed
	 */
	protected function findHomeTemplateByGroup($groupId)
	{
		if (empty($groupId)) {
			return false;
		}

		return $this->templateModel->find_home_template_by_group_id($groupId, $this->isShow);
	}

    /**
     * 处理首页分组数据
     * @author Jerry
     * @param $data
     * @param int $pageNumber
     * @return array|bool
     */
	protected function checkHomeTemplateGroupData($data, $pageNumber = 1)
	{
		if (empty($data)) {
			return false;
		}

//		当前可用首页
		$templateData = $this->findHomeTemplateByParentId($data['id']);

//		获取当前总模板数
        $pageSize = $this->templateStencilModel->findTemplateStencilCountNumberByTemplateId($templateData['id']);

//        预览首页
        if ($this->isShow) {
            $pageSize = $this->templateStencilModel->findTemplateStencilCountNumberByTemplateId($data['id']);
        }



//		没有可用时用最后一个首页
		if (empty($templateData)) {
		    $templateData = $this->getTemplateLastData($data['id']);
        }

        if ($data['id'] == 6) {
            $pageSize = $pageSize - 3;
        }


//        预览首页
		if (empty($templateData) && $this->isShow) {
			$stencil = $this->findTemplateStencilByTemplateId($data['id'], $pageNumber, $pageSize);
		}
		else{
			$stencil = $this->findTemplateStencilByTemplateId($templateData['id'], $pageNumber, $pageSize);
		}



		return $this->templateStencil($stencil, $pageNumber, $pageSize);
	}

    /**
     * @author Jerry
     * @param int $parentId
     * @return mixed
     */
	protected function getTemplateLastData($parentId = 0)
    {
        return $this->templateModel->getTemplateLastData($parentId);
    }

	/**
	 * Created by Jerry
	 * @param $parentId
	 * @return mixed
	 */
	protected function findHomeTemplateByParentId($parentId)
	{
		return $this->templateModel->find_home_template_by_parent_id($parentId, $this->isShow);
	}

    /**
     * @author Jerry
     * @param $templateId
     * @param int $pageNumber
     * @param int $pageSize
     * @return mixed
     */
	protected function findTemplateStencilByTemplateId($templateId, $pageNumber = 1, $pageSize = 0)
	{
		return $this->templateStencilModel->find_template_stencil_by_template_id($templateId, $pageNumber, $pageSize);
	}

    /**
     * 循环处理模块
     * @author Jerry
     * @param $stencils
     * @param int $pageNumber
     * @param int $pageSize
     * @return array
     */
	protected function templateStencil($stencils, $pageNumber = 1, $pageSize = 0)
	{
		if (empty($stencils)) {
			$this->setErrorMessage('暂无模块数据');
		}

		$data = array();
//		判断是否新用户
		$isNewUser = $this->getIsNewUser($this->userId);

		foreach ($stencils as $key => $value) {
//          老用户不显示
			if (($value['is_new_user'] == 1) && $isNewUser != 1) {
				continue;
			}
//          新用户不显示
			if (($value['is_new_user'] == 2) && $isNewUser != 0) {
			    continue;
            }

            //如果已经领取了满99元减少50的红包，则不显示新用户专享
            if ($value['name'] == '新用户专享' && !$this->show_bonus_new($this->userId)) {
                continue;
            }

			$stencil = $this->stencil($value['type'])->handle($value, $this->userId, $this->wid);

			if (empty($stencil)) {
				continue;
			}

			$stencil['border_size'] = 20;


			$data[] = $stencil;
		}

        $isLast = 0;
		$pageArr = show_page($pageSize, $pageNumber, 5);
        if ($pageNumber >= $pageArr['pagecount']) {
            $isLast = 1;
        }

         $result = array(
             'data' =>  $data,
             'page' =>  $pageArr,
             'is_bottom'     =>  $isLast,
         );

		 return $result;
	}

    /**
     * 检查是否领取了满99元减50红包
     * @param $user_id
     * @return bool
     */
	public function show_bonus_new($user_id){
	    $receive_key = 'user_new_bonus_receive_' . $user_id;
        $receive_no_key = 'user_new_bonus_no_receive_' . $user_id;

	    if (S($receive_key) == 1) {
            return false;
        }

        if (S($receive_no_key) == 1) {
            return true;
        }

        $bonus = C('NEW_USER_BONUS_ARRAY');

        $map = array('user_id' => $user_id,'bonus_type_id' => $bonus[0]);
        $count = M('user_bonus')->where($map)->count();
        if($count>0){
            S($receive_key, 1);
            return false;
        }else{
            S($receive_no_key, 1, 60);
            return true;
        }
    }

	/**
	 * 判断是否为新用户
	 * Created by Jerry
	 * @param int $user_id
	 * @return mixed
	 */
	public function getIsNewUser($user_id = 0)
	{
		if (empty($user_id)) {
			return false;
		}

		$key = 'is_new_user_key'.$user_id;

        $isNewUser = S($key);

        if ($isNewUser !== false) {
            return $isNewUser;
        }

		$isNewUser = D('Orderinfo')->isNewUser($user_id);

		if ($isNewUser == false) {
            S($key, 0);
			return 0;
		}

        S($key, 1, 60);
		return 1;
	}

	/**
	 * 处理模块数据
	 * Created by Jerry
	 * @param int $type
	 * @return HomeTemplateAdapter
	 */
	protected function stencil($type = 0)
	{
		return new HomeTemplateAdapter($type);
	}

	/**
	 * 设置错误信息
	 * Created by Jerry
	 * @param $message
	 * @return $this
	 */
	protected function setErrorMessage($message)
	{
		array_push($this->errorMessage, $message);
		return $this;
	}

	/**
	 * 返回专题名字
	 * Created by Jerry
	 * @param $groupId
	 * @return bool|mixed
	 */
	public function getHomeTemplateGroupName($groupId)
	{
		$group = $this->findHomeTemplateByGroup($groupId);

		if (empty($group)) {
			return false;
		}

		$templateParent = $this->findHomeTemplateByParentId($group['id']);

		if (empty($templateParent) && $this->isShow) {
			return $group;
		}

		return $templateParent;
	}

	public function handelGoodsBookBuy($homeTemplateData, $user_id)
    {
        $this->goodsRepository->userId = $user_id;
        $data = $homeTemplateData['data'];


        foreach ($data as $key => $val) {
            if ($val['type'] == 4) {

                if ($val['goods_list']) {
                    foreach ($val['goods_list'] as $k => $v) {

                        if ($v['goods_number'] == 0) {
                            //$data[$key]['goods_list'][$k]['is_book_goods'] = $this->goodsRepository->goodsBook($v['goods_id']);
                        }else{
                          //  $data[$key]['goods_list'][$k]['is_book_goods'] = 0;
                        }

                        $data[$key]['goods_list'][$k]['is_book_goods'] = 0;

                        $isBuy = $this->goodsRepository->isBuyGoodsByUserId($v['goods_id']);

                        $data[$key]['goods_list'][$k]['is_buy'] = $isBuy == true ? '1' : '0';

                    }
                }
            }
        }

        $homeTemplateData['data'] = $data;

        return $homeTemplateData;
    }


}